package org.springblade.modules.resource.service.impl;

import cn.hutool.core.date.DatePattern;
import cn.hutool.core.date.DateUtil;
import com.aliyun.oss.OSS;
import com.aliyun.oss.model.PutObjectResult;
import org.springblade.modules.alioss.model.FileOss;
import org.springblade.modules.resource.service.FileUploadService;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.Date;
import java.util.UUID;

@Service
public class AliyunOSSUploadServiceImpl implements FileUploadService {

    private final OSS ossClient;
    private final String bucketName;
    private final String urlPrefix;

    public AliyunOSSUploadServiceImpl(OSS ossClient,
                                     @Value("${aliyun.oss.bucket-name:}") String bucketName,
                                     @Value("${aliyun.oss.url-prefix:}") String urlPrefix) {
        this.ossClient = ossClient;
        this.bucketName = bucketName;
        this.urlPrefix = urlPrefix;
    }

    @Override
    public FileOss upload(MultipartFile file, String filePath) {
        try {
			makeBucket();
            // 上传文件
			PutObjectResult putObjectResult = ossClient.putObject(bucketName, filePath, file.getInputStream());
			// 返回文件访问URL
			FileOss fileOss = new FileOss();
			fileOss.setBucketName(bucketName);
			fileOss.setFullPath(urlPrefix +"/"+ filePath);
			fileOss.setPath(filePath);
			fileOss.setFileSize("");

			return fileOss;
        } catch (IOException e) {
            throw new RuntimeException("文件上传失败", e);
        }
    }

    private void makeBucket(){
		if (!ossClient.doesBucketExist(bucketName)) {
			ossClient.createBucket(bucketName);
		}
	}

    @Override
    public void delete(String filePath) {
        ossClient.deleteObject(bucketName, filePath);
    }

	@Override
	public String getFileName(String prefix, String originalFileName) {
		String fileExtension = originalFileName.substring(originalFileName.lastIndexOf("."));
		String fileName = UUID.randomUUID().toString() + fileExtension;

		// 组合文件路径

		return prefix+"/" + DateUtil.format(new Date(), DatePattern.PURE_DATE_PATTERN) + "/" + fileName;
	}
}
